package com.ywy.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.BootstrapWith;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.ywy.entity.User;
import com.ywy.service.impl.UsersServiceImpl;
import com.ywy.util.MD5Utils;

@Controller
@RequestMapping("user")
public class UsersController {

	@Autowired
	private UsersServiceImpl usi;

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param user_name
	 * @param user_pwd
	 * @return
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String userLogin(String user_name, String user_pwd) {

		
		boolean flag = usi.userLogin(user_name, MD5Utils.getEncodeByMd5(user_pwd));

		int userType = usi.selectUserByName(user_name).getUser_type();
		// 登录成功
		if(flag && userType == 1) {
			return "user/index";
		}
		else {
			return "user/login";
		}

	}

	/**
	 * 显示全部用户信息
	 */
	@RequestMapping(value = "userinfo", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView userInfo() {

		ModelAndView mv = new ModelAndView();
		List<User> list = usi.selectAllUsers();
		mv.addObject("list", list);
		mv.setViewName("admin/userlist");
		return mv;
	}

	/**
	 * 注册用户
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public String userRegister(String user_name,String user_pwd,String re_pwd,String tel,String addr) {
		
		User user = new User(0,user_name,MD5Utils.getEncodeByMd5(user_pwd),tel,addr,1);
		// 调用注册方法
		boolean flag = usi.addUser(user);

		// 如果注册成功
		boolean flag1 = usi.selectUserByName(user.getUser_name()).getUser_name().isEmpty();
		if(user_pwd.equals(re_pwd)) {
			
			if(!flag1 && flag) {
				
				return "user/login";
			}
			else {
				
				return "user/register";
			}
			
		}
		else {
			
			return "user/login";
		}
	}

}
